import * as types from './types';
import http from '../utils/https';

// 初始状态
// pans -> [{title,content,key}]
const initState = {
  navlist: [],
  panes: []
}

// 获取到相对应的数据返回给组件
export function navsidelist(state=initState,action) {
  switch(action.type) {
    case types.NAV_LIST:
    return {
      ...state,
      navlist: action.payload
    }
    case types.ADD_TAB: 
    return {
      ...state,
      panes: action.payload
    }
    case types.ACTIVE_TAB:
    return {
      ...state,
      panes: action.payload
    }
    case types.REMOVE_TAB: 
    return {
      ...state,
      panes: action.payload
    }

    default:
    return state
  }
}
// navlist 分析type
function navlist(data) {
  return {
    type: types.NAV_LIST,
    payload: data
  }
}

// 获取相navlist
export function getSideList() {
  return async dispatch=> {
    const res = await http.get('/api/navsidelist')
    if (res.status === 200) {
      dispatch(navlist(res.data.data))
    }
  }
}

// menu 获取相对tab选项卡
// add tabs
const _cachePanes = [];
export function addTab(pane) {
  let _cachTabs = {"title": pane.title,"isOpen": pane.isOpen,"url":pane.url,"key":pane.key,"icon":pane.icon}
  let flag = true;
  _cachePanes.map(v => {
      return v.title === pane.title ? (flag = false,v.isOpen = true) : (flag,v.isOpen= false) 
  })

  if(flag) {
    _cachePanes.push(_cachTabs)
    return {
      type: types.ADD_TAB,
      payload: _cachePanes
    }
  } else {
    return activeTab(_cachePanes.filter(v => v.isOpen))
  }

}

// menu 获取相对tab选项卡
// remove tabs
let _retremoveArray = [];
export function removeTab(removeKyes) {
  [..._retremoveArray] = _cachePanes;
  if(_cachePanes.length > 0) {
    var index = 0;
    _cachePanes.forEach(v => {
      index++
      if(v.url === removeKyes) {
        // 把原数组里面的也删了...
        _cachePanes.splice(index-1, 1)
        _retremoveArray.splice(index-1, 1)
        _retremoveArray[_retremoveArray.length-1].isOpen=true
      } 
    })
  }
  return {
    type: types.REMOVE_TAB,
    payload: _retremoveArray
  }
}

// active 激活相对应的tab菜单
// active tab
export function activeTab(active) {
  let active_filter = [];
  [...active_filter] = _cachePanes;
  if(_cachePanes.length > 0) {
    active_filter.map(v => v.url === active.url ? v.isOpen = true:null)
  }
  return {
    type: types.ACTIVE_TAB,
    payload: active_filter
  }
}
